package com.mimo.push.config;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.mimo.common.rpc.proto.CometMessageProxyGrpc;

import net.devh.boot.grpc.client.inject.GrpcClient;

@Component
public class CometMsgPoolFactory {

  private final Map<String, CometMessageProxyGrpc.CometMessageProxyBlockingStub> holder = new HashMap<>();

  @Value("${comet.server-1.url}")
  private String cometServer1;

  @Value("${comet.server-2.url}")
  private String cometServer2;

  @Value("${comet.server-3.url}")
  private String cometServer3;

  @PostConstruct
  public void init() {
    holder.put(cometServer1, cometMessageProxyBlockingStub1);
    holder.put(cometServer2, cometMessageProxyBlockingStub2);
    holder.put(cometServer3, cometMessageProxyBlockingStub3);
  }

  @GrpcClient(value = "comet-msg-1")
  private CometMessageProxyGrpc.CometMessageProxyBlockingStub cometMessageProxyBlockingStub1;

  @GrpcClient(value = "comet-msg-2")
  private CometMessageProxyGrpc.CometMessageProxyBlockingStub cometMessageProxyBlockingStub2;

  @GrpcClient(value = "comet-msg-3")
  private CometMessageProxyGrpc.CometMessageProxyBlockingStub cometMessageProxyBlockingStub3;

  public CometMessageProxyGrpc.CometMessageProxyBlockingStub getCometMessageStub(String ip, Integer port) {
    CometMessageProxyGrpc.CometMessageProxyBlockingStub stub = holder.get(ip + ":" + port);
    if (Objects.isNull(stub)) {
      throw new IllegalArgumentException(String.format("remote comet : ip[%s], port[%s] 未被正确配置", ip, port));
    }
    return stub;
  }
}
